//路由守卫
import router from '@/router'
import utils from "@/utils"
import { menuRoleList } from "@/apis/systemManaging/menu";
import { useUserStore } from '@/stores/user';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
let flag=true;
NProgress.configure({ showSpinner: false }); // 进度条
router.beforeEach(async (to, from, next) => {
    NProgress.start();
    document.title = `${to.meta.title}-${import.meta.env.VITE_APP_TITLE}`;
    const userStore = useUserStore();
    const token = userStore.token;
    if (token) {
        if (to.path == '/login') {
            next({ path: '/' })
            NProgress.done();
        }
        const menuRes = await menuRoleList();
        let routerList = null;
        if (flag&&menuRes.code === 200) {
            routerList = utils.addRouter(menuRes.data);
            userStore.changeMenuList(routerList);
            routerList.forEach(item => {
                router.addRoute('mainHome', item)
            })
            router.addRoute({
                path: '/404',
                component: () => import('@/views/error/404.vue'),
                meta: {
                    title: '404',
                    hidden: true,
                    icon: 'DocumentDelete',
                },
            })
            router.addRoute({
                path: '/:pathMatch(.*)*',
                redirect: '404',
            });
            flag=false;
            next({ ...to, replace: true })
        }else{
            NProgress.done();
            next()
        }
    } else {
        if (to.path !== '/login') {
            next({ path: '/login' })
        }
        next()
        NProgress.done();
    }
})
router.afterEach(() => {
    NProgress.done();
})